package com.example.himalaya;

import android.animation.ValueAnimator;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.*;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;
import androidx.viewpager.widget.ViewPager;
import com.example.himalaya.adapters.PlayerTrackPagerAdapter;
import com.example.himalaya.base.BaseActivity;
import com.example.himalaya.interfaces.IPlayCallBack;
import com.example.himalaya.presenters.PlayerPresenter;
import com.example.himalaya.utils.LogUtil;
import com.example.himalaya.views.SobPopWindow;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.*;

public class PlayerActivity extends BaseActivity implements IPlayCallBack, ViewPager.OnPageChangeListener {
    private PlayerPresenter mPlayerPresenter;
    private ImageView mControlBtn;
    private SimpleDateFormat mMinFormat = new SimpleDateFormat("mm:ss");
    private SimpleDateFormat mHourFormat = new SimpleDateFormat("hh:mm:ss");
    private TextView mTotalDuration;
    private TextView mCurrentPosition; //当前的播放进度时间
    private SeekBar mDurationBar;
    private int mCurrentProgress = 0; //播放器当前进度
    private boolean mIsUserTouchProgressBar = false; //用手拖动
    private ImageView mPlayPre;
    private ImageView mPlayNext;
    private TextView mTrackTitleTv;
    private String mTrackTitleText;
    private ViewPager mTrackPageView;
    private final static String TAG = "PlayerActivity";
    private PlayerTrackPagerAdapter mTrackPagerAdapter;
    private boolean mIsUserSlidePager = false;//判断是否是用户用手触摸
    private ImageView mPlayModeSwitchBtn;
    private ImageView mPlayListBtn;
    private SobPopWindow mSobPopWindow;
    private ValueAnimator mEnterBgAnimation;
    private ValueAnimator mOutBgAnimation;




    //播放模式
    private XmPlayListControl.PlayMode mCurrentMode = XmPlayListControl.PlayMode.PLAY_MODEL_LIST;
    private static Map<XmPlayListControl.PlayMode, XmPlayListControl.PlayMode> sPlayModeRule = new HashMap<>();
    /**
     * 处理播放模式的切换
     * 1、列表播放：PLAY_MODEL_LIST（默认）
     * 2、列表循环：PLAY_MODEL_LIST_LOOP
     * 3、随机播放：PLAY_MODEL_RANDOM
     * 4、单曲循环：PLAY_MODEL_SINGLE_LOOP
     * */
    static {
        sPlayModeRule.put(PLAY_MODEL_LIST, PLAY_MODEL_LIST_LOOP);
        sPlayModeRule.put(PLAY_MODEL_LIST_LOOP, PLAY_MODEL_RANDOM);
        sPlayModeRule.put(PLAY_MODEL_RANDOM, PLAY_MODEL_SINGLE_LOOP);
        sPlayModeRule.put(PLAY_MODEL_SINGLE_LOOP, PLAY_MODEL_LIST);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);
        mPlayerPresenter = PlayerPresenter.getPlayerPresenter();
        mPlayerPresenter.registerViewCallBack(this);
        initView();
        //在控件界面初始化以后再去获取数据
        mPlayerPresenter.getPlayList();
        initEvent();
        startPlay();
        initBgAnimation();
    }

    //专辑播放列表出现的动画效果
    private void initBgAnimation() {
        //进入时的动画效果
        mEnterBgAnimation = ValueAnimator.ofFloat(1.0f,0.7f);
        mEnterBgAnimation.setDuration(500);
        mEnterBgAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                //处理背景，需要有透明度
                updateBgAplha(value);
            }
        });

        //退出时的动画效果
        mOutBgAnimation = ValueAnimator.ofFloat(0.7f,1.0f);
        mOutBgAnimation.setDuration(500);
        mOutBgAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                //处理背景，需要有透明度
                updateBgAplha(value);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //销毁释放资源
        if (mPlayerPresenter != null) {
            mPlayerPresenter.unRegisterViewCallBack(this);
            mPlayerPresenter = null;
        }
    }

    /**
     * 初始化控件
     * */
    private void initView() {
        mControlBtn = this.findViewById(R.id.play_or_pause_btn);
        mTotalDuration = this.findViewById(R.id.track_duration);
        mCurrentPosition = this.findViewById(R.id.current_position);
        mDurationBar = this.findViewById(R.id.track_seek_bar);
        mPlayPre  = this.findViewById(R.id.play_pre);
        mPlayNext = this.findViewById(R.id.play_next);
        mTrackTitleTv = this.findViewById(R.id.track_title);
        if (!TextUtils.isEmpty(mTrackTitleText)) {
            mTrackTitleTv.setText(mTrackTitleText);
        }
        mTrackPageView = this.findViewById(R.id.track_pager_view);
        //创建适配器
        mTrackPagerAdapter = new PlayerTrackPagerAdapter();
        //设置适配器
        mTrackPageView.setAdapter(mTrackPagerAdapter);
        //切换播放模式的按钮
        mPlayModeSwitchBtn = findViewById(R.id.player_mode_switch_btn);
        //播放列表
        mPlayListBtn = this.findViewById(R.id.player_list);
        mSobPopWindow = new SobPopWindow();

    }

    /**
     * 初始化控件的事件
     * */
    private void initEvent() {
        mControlBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //如果当前状态是播放，将暂停;如果是暂停就播放
                if (mPlayerPresenter.isPlay()){
                    mPlayerPresenter.pause();
                }else {
                    mPlayerPresenter.play();
                }
            }
        });
        //手拖动进度条触发事件
        mDurationBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean isFromUser) {
                if (isFromUser){
                    mCurrentProgress = progress;
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                mIsUserTouchProgressBar = true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mIsUserTouchProgressBar = false;
                //手离开拖动进度条的时候更新进度
                mPlayerPresenter.seekTo(mCurrentProgress);
            }
        });
        //播放上一首
        mPlayPre.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPlayerPresenter != null){
                    mPlayerPresenter.playPre();
                }
            }
        });
        //播放下一首
        mPlayNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPlayerPresenter != null) {
                    mPlayerPresenter.playNext();
                }
            }
        });
        //判断用户是否触屏
        mTrackPageView.addOnPageChangeListener(this);
        mTrackPageView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                switch (action){
                    case MotionEvent.ACTION_DOWN:
                        mIsUserSlidePager = true;
                        break;
                }
                return false;
            }
        });

        //播放模式
        mPlayModeSwitchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //根据当前的mode找到下一个mode
                XmPlayListControl.PlayMode  playMode = sPlayModeRule.get(mCurrentMode);
                //修改播放模式
                if (mPlayerPresenter != null) {
                    mPlayerPresenter.switchPlayMode(playMode);
                    mCurrentMode = playMode;
                    updatePlayModeBtnImg();
                    mSobPopWindow.updatePlayMode(mCurrentMode);
                }
            }
        });

        //专辑列表按钮
        mPlayListBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //展示播放列表
                mSobPopWindow.showAtLocation(v, Gravity.BOTTOM,0,0);//出现的专辑列表栏居于画面底部
                //修改背景透明度
                mEnterBgAnimation.start();
            }
        });

        //PopWindow消失以后恢复正常的透明度
        mSobPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                //pop窗体消失以后，恢复透明度
                mOutBgAnimation.start();
            }
        });

        mSobPopWindow.setPlayListItemClickListener(new SobPopWindow.PlayListItemClickListener() {
            @Override
            public void onItemClick(int position) {
                //当播放列表里的item被点击后，切换到被点击的歌曲
                if (mPlayerPresenter != null) {
                    mPlayerPresenter.playByIndex(position);
                }
            }
        });

        //播放列表切换播放模式
        mSobPopWindow.setPlayListPlayModeClickListener(new SobPopWindow.PlayListPlayModeClickListener() {
            @Override
            public void onPlayModeClick() {
                //根据当前的mode找到下一个mode
                XmPlayListControl.PlayMode  playMode = sPlayModeRule.get(mCurrentMode);
                //修改播放模式
                if (mPlayerPresenter != null) {
                    mPlayerPresenter.switchPlayMode(playMode);
                    mCurrentMode = playMode;
                    mSobPopWindow.updatePlayMode(mCurrentMode);
                    updatePlayModeBtnImg();
                }
            }
        });

    }

    //切换播放模式的功能函数
    private void switchPlayMode() {
        //根据当前的mode找到下一个mode
        XmPlayListControl.PlayMode  playMode = sPlayModeRule.get(mCurrentMode);
        //修改播放模式
        if (mPlayerPresenter != null) {
            mPlayerPresenter.switchPlayMode(playMode);
            mCurrentMode = playMode;
            updatePlayModeBtnImg();

        }
    }

    private void updateBgAplha(float alpha) {
        Window window = getWindow();
        WindowManager.LayoutParams attributes = window.getAttributes();
        attributes.alpha = alpha;
        window.setAttributes(attributes);
    }

    /**
     * 根据当前状态更新播放模式的图标
     * 1、列表播放：PLAY_MODEL_LIST（默认）
     * 2、列表循环：PLAY_MODEL_LIST_LOOP
     * 3、随机播放：PLAY_MODEL_RANDOM
     * 4、单曲循环：PLAY_MODEL_SINGLE_LOOP
     * */
    private void updatePlayModeBtnImg() {
        int resID = R.drawable.selector_play_mode_list_order;
        switch (mCurrentMode){
            case PLAY_MODEL_LIST:
                resID = R.drawable.selector_play_mode_list_order;
                break;
            case PLAY_MODEL_RANDOM:
                resID = R.drawable.selector_paly_mode_random;
                break;
            case PLAY_MODEL_LIST_LOOP:
                resID = R.drawable.selector_paly_mode_list_order_looper;
                break;
            case PLAY_MODEL_SINGLE_LOOP:
                resID = R.drawable.selector_paly_mode_single_looper;
                break;
        }
        mPlayModeSwitchBtn.setImageResource(resID);
    }

    /**
     * 开始播放
     * */
    private void startPlay() {
        if (mPlayerPresenter != null) {
            mPlayerPresenter.play();
        }
    }

    @Override
    public void onPlayStart() {
        //开始播放以后将播放图标修改为暂停图标
        if (mControlBtn != null) {
            mControlBtn.setImageResource(R.mipmap.stop_press);
        }

    }

    @Override
    public void onPlayPause() {
        if (mControlBtn != null) {
            mControlBtn.setImageResource(R.mipmap.play_press);
        }

    }

    @Override
    public void onPlayStop() {
        if (mControlBtn != null) {
            mControlBtn.setImageResource(R.mipmap.play_press);
        }
    }

    @Override
    public void onPlayError() {
    }

    @Override
    public void nextPlay(Track track) {
        if (mPlayNext != null){
            mPlayNext.setImageResource(R.mipmap.previous_press);
        }
    }

    @Override
    public void onPrePlay(Track track) {
        if (mPlayPre != null){
            mPlayNext.setImageResource(R.mipmap.next_press);
        }
    }

    @Override
    public void onListLoaded(List<Track> list) {
        LogUtil.d(TAG,"onListLoaded ------->"+list);
        if (mTrackPagerAdapter != null) {
            mTrackPagerAdapter.setData(list);
        }
        //数据回来以后，也要给节目列表一份。
        if (mSobPopWindow != null) {
            mSobPopWindow.setListData(list);
        }
    }

    @Override
    public void onPlayModeChange(XmPlayListControl.PlayMode playMode) {
    }

    @Override
    public void onProgressChange(int currentProgress, int total) {
        mDurationBar.setMax(total);
        //更新播放进度 -->转换为分钟、小时
        String totalDuration;
        String currentPosition;
        if (total > 1000*60*60){
            totalDuration = mHourFormat.format(total);
            currentPosition = mHourFormat.format(currentProgress);
        }else {
            totalDuration = mMinFormat.format(total);
            currentPosition = mMinFormat.format(currentProgress);
        }
        //更新当前时间
        if (mTotalDuration != null) {
            mTotalDuration.setText(totalDuration);
        }
        if (mCurrentPosition != null) {
            mCurrentPosition.setText(currentPosition);
        }
        //更新进度条
        if (!mIsUserTouchProgressBar){
//            int percent = (int) (currentProgress *1.0f / total *100);
            mDurationBar.setProgress(currentProgress);
        }
    }

    @Override
    public void onAdLoading() {
    }

    @Override
    public void onAdFinished() {
    }

    @Override
    public void onTrackUpdate(Track track,int playIndex){
        this.mTrackTitleText = track.getTrackTitle();
        if (mTrackTitleTv != null) {
            //设置当前节目的标题
            mTrackTitleTv.setText(mTrackTitleText);
        }
        //当前节目改变的时候，其海报也要改变
        if (mTrackPageView != null) {
            mTrackPageView.setCurrentItem(playIndex,true); //true表示海报切换的时候有动画
        }
        //设置播放列表里当前播放的位置
        if (mSobPopWindow != null) {
            mSobPopWindow.setCurrentPlayPosition(playIndex);
        }


    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
        //当专辑页面选中的时候就去切换播放内容,并且判断是否为用户操作
        if (mPlayerPresenter != null && mIsUserSlidePager) {
            mPlayerPresenter.playByIndex(position);
        }
        mIsUserSlidePager = false;
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }
}